<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增评估')"/>
    <th:block th:include="include :: select2-css"/>
    <th:block th:include="include :: layout-latest-css"/>

</head>
<body>
<div class="main-content">
    <form id="form-user-add" class="form-horizontal">
        <h4 class="form-header h4">基础信息</h4>
        <div class="row">
            <div class="col-sm-4">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">测评名称：</label>
                    <div class="col-sm-8">
                        <input name="aTitle" placeholder="请输入测评名称，最多20位" class="form-control" type="text"
                               maxlength="20" required>
                    </div>
                </div>
            </div>

            <div class="col-sm-4">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">攻击类型：</label>
                    <div class="col-sm-8">
                        <select onchange="onchangeAttackType()" id="aType" name="aType" class="form-control m-b"
                                th:with="type=${@dict.getType('attack_type')}">
                            <option th:each="dict : ${type}" th:text="${dict.dictLabel}"
                                    th:value="${dict.dictValue}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-sm-4">
                <div class="form-group ">
                    <label class="col-sm-4 control-label">时间段：</label>
                    <div class="col-sm-8 select-time">
                        <input name="aTime" readonly data-type="date" placeholder="-" class="form-control time-input-two" type="text" maxlength="30" required>
                    </div>
                </div>
                <!--<div class="form-group">
                    <label class="col-sm-3 control-label">时间段：</label>
                    <div class="col-sm-8">
                        <input id="startTime"  name="params[startTime]"  class="time-input form-control" format="yyyy-MM-dd HH:mm:ss" data-type="datetime"  th:value="*{#dates.format(new java.util.Date().getTime(), 'yyyy-MM-dd HH:mm:ss')}">
                   <span>-</span>
                        <input id="endTime" name="params[endTime]" class="time-input form-control" format="yyyy-MM-dd HH:mm:ss" data-type="datetime"  th:value="*{#dates.format(new java.util.Date().getTime(), 'yyyy-MM-dd HH:mm:ss')}">
                    </div>
                </div>-->
            </div>
        </div>
        <div class="row">
            <div class="col-sm-4">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">自定义攻击系数（DBT）：</label>
                    <div class="col-sm-8">
                        <input id="aRate" name="aRate" class="form-control" type="number" th:value="${v1}"
                               maxlength="11" required>
                    </div>
                </div>
            </div>
            <div class="col-sm-4">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">完整系数权重（q1）：</label>
                    <div class="col-sm-8">
                        <input id="aQ1" name="aQ1" class="form-control" type="number" th:value="${v2}" maxlength="20"
                               required>
                    </div>
                </div>
            </div>
            <div class="col-sm-4">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required"> 关联系数权重（q2）：</label>
                    <div class="col-sm-8">
                        <input id="aQ2" name="aQ2" class="form-control" type="number" th:value="${v3}" maxlength="20"
                               required>
                    </div>
                </div>
            </div>
        </div>

    </form>
    <h4 class="form-header h4">完整性要素 <span class="font-red" val="0.0" id="p1">p1=0.0</span></h4>


    <div class="col-sm-12 select-table table-striped">
        <table id="table1"></table>
    </div>

    <h4 class="form-header h4">关联性要素 </h4>
    <div class=" select-table table-striped col-sm-8">
        <table id="table2"></table>
    </div>

    <h4 class="form-header h4">关联要素组合比率和累计比率 <span class="font-red" val="0.0" id="p2">p1=0.0</span></h4>

    <div class=" select-table table-striped col-sm-12">
        <table id="table3"></table>
    </div>


    <h4 class="form-header h4 pull-left">专家打分</h4>
    <a class="btn btn-success " id="toolbar4" onclick="insertRow()">
        <i class="fa fa-plus"></i> 新增打分
    </a>
    <div class="col-sm-12 select-table table-striped">
        <table id="table4"></table>
    </div>

    <h4 class="form-header h4 pull-left">攻击概率（p） </h4>
    <div class="row  pull-left">
        <span class="font-red" id="attack-p">p=0.0</span>
    </div>


</div>

<div class="row">
    <div class="col-sm-offset-5 col-sm-10">
        <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>提 交
        </button><!--&nbsp;-->
        <button type="button" class="btn btn-sm btn-danger" onclick="refreshItem()"><i class="fa fa-reply-all"></i>重 置
        </button>
    </div>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: select2-js"/>
<script>
    var prefixSave = ctx + "system/attack";

    function submitHandler() {
        if ($.validate.form()) {

            var data = $("#form-user-add").serializeObject();

            var wzxs = getData('table1');
            var glxs = getSelectData('table2');
            var scores = getData('table4');


            data.wzxs = wzxs;
            data.glxs = glxs;
            data.scores = scores;
            data.aP1 = $('#p1').attr('val');
            data.aP2 = $('#p2').attr('val');

            $.ajax({
                url: prefixSave + "/add",
                type: "post",
                dataType: "json",
                data: data,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍后...");
                    $.modal.disable();
                },
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msgSuccess(result.msg);
                    } else if (result.code == web_status.WARNING) {
                        $.modal.alertWarning(result.msg)
                    } else {
                        $.modal.alertError(result.msg);
                    }
                    $.modal.closeLoading();
                    $.modal.enable();
                }
            });

        } else {
            $.modal.msgWarning("表单填写错误");
        }
    }


</script>

<th:block th:include="include :: footer"/>
<script th:inline="javascript">
    //--------------------------第一个表格---------------------------
    var editFlag = [[${@permission.hasPermi('system:wzs:edit')}]];
    var removeFlag = [[${@permission.hasPermi('system:wzs:remove')}]];
    var prefix = ctx + "system/wzs";

    var dataTable1 = {};
    $(function () {
        var vs = $('select  option:selected').val();
        var params = "c_type=1"
        if (vs == 'type_destroy') {
            params = "c_type=1";
        } else if (vs == 'type_robbery') {
            params = "c_type=2";
        }
        initTable1(params);
    });

    function onchangeAttackType() {
        var vs = $('select  option:selected').val();
        var params = "c_type=1"
        if (vs == 'type_destroy') {
            params = "c_type=1";
        } else if (vs == 'type_robbery') {
            params = "c_type=2";
        }
        $.table.destroy("table1")
        initTable1(params);

    }

    /* 标记状态 */
    function statusTools(row) {
        if (row.aChas == 1) {
            return '<i class=\"fa fa-toggle-on text-info fa-2x\" onclick="disable(\'' + row.aCid + '\')"></i> ';

        } else {
            return '<i class=\"fa fa-toggle-off text-info fa-2x\" onclick="enable(\'' + row.aCid + '\')"></i> ';

        }

    }

    /* 不存在 */
    function disable(aCid) {
        $(dataTable1.rows).each(function (i, e) {
            if (e.aCid == aCid) {
                e.aChas = 2;
                $("#table1").bootstrapTable("load", dataTable1)
            }
        });
        setP1(dataTable1.rows);
    }

    /* 存在 */
    function enable(aCid) {
        $(dataTable1.rows).each(function (i, e) {
            if (e.aCid == aCid) {
                e.aChas = 1;
                $("#table1").bootstrapTable("load", dataTable1)
            }
        });
        setP1(dataTable1.rows);
    }

    //初始化第一个表格
    function initTable1(params) {
        var options = {
            /**破坏*/
            url: prefix + "/list?" + params,
            createUrl: prefix + "/add",
            updateUrl: prefix + "/edit_in_attack/{id}",
            removeUrl: prefix + "/remove",
            exportUrl: prefix + "/export",
            modalName: "完整性要素",
            id: 'table1',
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            showSearch: false,
            pagination: false,
            onLoadSuccess: function (data) {
                dataTable1 = data;
                setP1(data.rows);
            },
            columns: [
                {
                    title: "编号（n）",
                    formatter: function (value, row, index) {
                        return $.table.serialNumber(index);
                    }
                },
                {
                    field: 'aCname',
                    title: '要素名称'
                },
                {
                    field: 'aCweight',
                    title: '权重系数'
                },
                {
                    title: '标记出现',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return statusTools(row);
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="editTable1(\'' + row.aCid + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);
    }

    //计算p1的值
    function setP1(rows) {
        //计算 p1
        var p1 = 0.0;
        if (rows && rows.length > 0) {
            $(rows).each(function (i, e) {
                if (e.aChas == 1) {
                    p1 += (i + 1) * e.aCweight;
                }
            })
            p1 = p1 / rows.length;

            p1 = format45(p1, 10000);

            $('#p1').text('p1 = ' + p1);
            $('#p1').attr('val', p1)

        } else {
            $('#p1').text('p1 = ' + 0.0);
            $('#p1').attr('val', 0.0)
        }
        setAttackRate();

    }

    //修改数据
    function editTable1(aCid) {
        $(dataTable1.rows).each(function (i, e) {
            if (e.aCid == aCid) {
                window.localStorage.setItem('aCid_' + aCid, JSON.stringify(e));
            }
        });

        table.set();
        $.modal.open("修改" + table.options.modalName, $.operate.editUrl(aCid), null, null, function (index, layero) {
            var back = $(layero).find('iframe')[0].contentWindow.submitHandler(index, layero);
            ;

            $(dataTable1.rows).each(function (i, e) {
                if (e.aCid == aCid) {
                    e.aChas = back.aChas;
                    e.aCname = back.aCname;
                    e.aCweight = back.aCweight;
                    e.remark = back.remark;
                }
            });
            $("#table1").bootstrapTable("load", dataTable1)
            setP1(dataTable1.rows);
            $.modal.closeAll();
        });
    }

    //--------------------------第一个表格结束---------------------------
</script>

<script th:inline="javascript">

    var prefix2 = ctx + "system/glx";
    var dataTable2 = {};
    $(function () {
        //破坏
        var options2 = {
            url: prefix2 + "/list?c_type=4",
            createUrl: prefix2 + "/add?c_type=4",
            updateUrl: prefix2 + "/edit/{id}",
            removeUrl: prefix2 + "/remove",
            exportUrl: prefix2 + "/export",
            modalName: "关联性要素",
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            showSearch: false,
            pagination: false,
            id: 'table2',
            onLoadSuccess: function (data) {
                dataTable2 = data;
                // initTable3(data.rows.length);
                initTable3(0);
            }, onCheckAll: function (rows) {
                var count = getSelectData("table2").length;
                $.table.destroy('table3');
                initTable3(count);
            }, onCheck: function (row) {
                var count = getSelectData("table2").length
                $.table.destroy('table3');
                initTable3(count);
            }, onUncheck: function (row) {
                var count = getSelectData("table2").length
                $.table.destroy('table3');
                initTable3(count);
            }, onUncheckAll: function (row) {
                var count = getSelectData("table2").length
                $.table.destroy('table3');
                initTable3(count);
            }, onClickRow: function () {

            },
            columns: [{
                checkbox: true,
            }, {
                title: "序号",
                formatter: function (value, row, index) {
                    return $.table.serialNumber(index);
                }
            },

                {
                    field: 'aCname',
                    title: '要素名称',


                },
                {
                    field: 'createTime',
                    title: '创建时间'
                }]
        };
        $.table.init(options2);
    });


    function getSelectData(id) {
        // 获取当前行
        var rows = $('#' + id).bootstrapTable('getSelections');
        return rows;
    }

    //计算第三个表格
    function initTable3(count) {
        var prefix3 = ctx + "system/attack/getCanKaoData?count=" + count;
        var dataTable3;
        var options3 = {
            url: prefix3,
            modalName: "关联性要素",
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            showSearch: false,
            pagination: false,
            id: 'table3',
            onLoadSuccess: function (data) {
                dataTable3 = data;
                setP2();
            },
            columns: [
                {
                    field: 'title',
                    title: '正关联要素数目'
                }]
        };

        for (var i = 2; i <= count; i++) {
            options3.columns.push(
                {
                    field: 'c_' + i,
                    title: i
                }
            )
        }
        $.table.init(options3);
    }


</script>
<th:block th:include="include :: bootstrap-table-editable-js"/>
<script th:inline="javascript">
    var pe = [];
    $(function () {
        var options4 = {
            data: {rows: [], total: 0},
            showSearch: false,
            showRefresh: false,
            showToggle: false,
            showColumns: false,
            pagination: false,
            id: 'table4',
            toolbar: "toolbar4",
            onEditableSave: setP2,
            columns: [
                {
                    title: "序号",
                    formatter: function (value, row, index) {
                        return $.table.serialNumber(index);
                    }
                },
                {
                    field: 'aSid',
                    title: 'id',
                    visible: false,
                }, {
                    field: 'aSname',
                    title: '专家名称'

                },
                {
                    field: 'aSvalue',
                    title: '关联性要素个数',
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<span class="btn btn-danger btn-xs"  onclick="removeRow(\'' + row.aSid + '\')"><i class="fa fa-remov "></i >删除</span>');
                        return actions.join('');
                    }
                }
            ], /**
             * @param {点击列的 field 名称} field
             * @param {点击列的 value 值} value
             * @param {点击列的整行数据} row
             * @param {td 元素} $element
             */
            onClickCell: function (field, value, row, $element) {
                if (field == 'aSname' || field == 'aSvalue') {

                    if (pe.length > 0) {
                        $(pe[0]).blur();
                        pe.slice(0, 1);
                    }
                    pe.push($element);
                    $element.attr('contenteditable', true);
                    $element.focus();
                    $element.blur(function () {
                        let index = $element.parent().data('index');
                        let tdValue = $element.html();

                        saveData(index, field, tdValue);
                    })
                }
            }
        };
        $.table.init(options4);


        ///更新表格数据
        function saveData(index, field, value) {
            $("#table4").bootstrapTable('updateCell', {
                index: index,       //行索引
                field: field,       //列名
                value: value,      //cell值
            });
            setP2();
        }
    });

    /* 新增表格行 */
    function insertRow() {
        var randomId = 100 + ~~(Math.random() * 1000)
        $("#table4").bootstrapTable('insertRow', {
            index: 0, // 你想插入到哪，0表示第一行
            row: {
                aSid: randomId,
                aSname: '',
                aSvalue: '',
            }
        });

    }

    /* 删除指定表格行 */
    function removeRow(aSid) {
        var data = getData();

        $(data).each(function (i, e) {
            if (e.aSid == aSid) {
                data.splice(i, 1);
            }
        });
        $("#table4").bootstrapTable("load", {rows: data, total: data.length})
        setP2();
    }

    /* 查询表格所有数据值 */
    function getData(table) {
        var data;
        if (table) {
            data = $("#" + table).bootstrapTable('getData');
        } else {
            data = $("#table4").bootstrapTable('getData');
        }
        return data;
    }


    //计算p1的值
    function setP2() {
        //打分
        var rows = getData();

        if (rows && rows.length > 0) {
            //计算 p1
            var p2 = 0.0;
            $(rows).each(function (i, e) {
                if (e.aSvalue && e.aSvalue > 0) {
                    p2 += getRate(e.aSvalue);
                }
            })
            p2 = p2 / rows.length
            p2 = format45(p2, 10000)
            $('#p2').text('p2 = ' + p2);
            $('#p2').attr('val', p2)

        } else {
            $('#p2').text('p2 = ' + 0.0);
            $('#p2').attr('val', 0.0)
        }
        setAttackRate();
    }

    //计算概率。


    //打分的平均分
    function getRate(aSvalue) {
        var data = $("#table3").bootstrapTable('getData');

        var rate = data[0];
        var rateAll = data[1];

        var element = rateAll['c_' + aSvalue];
        if (element) {
            return parseFloat(element);
        } else {
            return 0.0;

        }
    }

    //计算最攻击概率

    function setAttackRate() {

        var q1 = $('#aQ1').val();
        var q2 = $('#aQ2').val();
        var p1 = $('#p1').attr('val');
        var p2 = $('#p2').attr('val');
        var rate = 0.5 * (q1 * p1 + q2 * p2);
        rate = format45(rate, 10000);
        $('#aRate').val(rate);
        $('#attack-p').text('p =' + rate);

    }

    //校验是否为数字
    function test(num) {
        if (num == '') {
            return false;
        }
        if (!(/(^[2-9]\d*$)/.test(num))) {
            return false;
        } else {
            return true;
        }
    }

    function format45(val, v2) {
        if (isNaN(val) || val == undefined || val == null) {
            return null;
        }
        return Math.round(val * v2) / v2;
    }

    //format45(748.586767, 10000)  //结果：748.5868
</script>
</body>
</html>